<?php
/**
 * Created by PhpStorm.
 * User: Duyonggao
 * Date: 2018/1/23 0023
 * Time: 下午 2:00
 */

namespace backend\controllers;


use common\Com\Caiji;
use common\Com\CurlMatch;
use common\models\Help;
use common\models\MobileDetail;
use common\utils\Api;
use common\utils\Com;
use common\utils\Curl;
use yii\data\Pagination;
use yii\web\Controller;
use common\traits\Response;

class TestController extends Controller
{
    use Response;
    public function actionIndex(){
        $help = Help::findOne(1);
        $str = $help->content;
        preg_match_all('/<p>(.*?)<\/p>/',$str,$out);
        var_dump($out);
    }

    public function actionUrl(){
        if(\Yii::$app->request->isAjax){
            $url = \Yii::$app->request->post('url');
            if(empty($url)){
                return $this->ajaxError();
            }
            $curl = new Curl();
            $html = $curl->get($url);
            preg_match_all('/<a(.*?)href=[\'"](.*?)[\'"](.*?)>(.*?)<\/a>/',$html->response,$out);
            $str = '';
            if(isset($out[2]) && count($out[2]) > 0){
                foreach($out[2] as $link){
                    $str .= '<p><a href="'.$link.'">'.$link.'</a></p>';
                }
            }
            return $this->ajaxSuccess(['url'=>$str]);
        }
        return $this->render("url");
    }

    public function actionMobile(){
        if(\Yii::$app->request->isAjax){
            $url = \Yii::$app->request->post('url');
            if(empty($url)){
                return $this->ajaxError();
            }
            $url = trim($url);
            $arr =explode("\n",$url);
            if(count($arr) == 1){
                foreach ($arr as $item){
                    if(!empty($item) && Com::isMobileNum($item)){
                        $detail = Api::mobileDetail_tb($item);
                        if(!empty($detail)){
                            $exit = MobileDetail::find()->where(['mobile'=>$detail['telString']])->exists();
                            if(empty($exit)){
                                $row = new MobileDetail();
                                $row->mobile = $detail['telString'];
                                $row->province = $detail['province'];
                                $row->operator = $detail['catName'];
                                $row->save();
                            }
                        }
                        return $this->ajaxSuccess($detail);
                    }
                }
            }
            if(count($arr) > 0){
                $arr = array_unique($arr);
                return $this->ajaxSuccess($arr);
            }
            return $this->ajaxError();
        }
        return $this->render("mobile");
    }

    public function actionUnique(){
        if(\Yii::$app->request->isAjax){
            $url = \Yii::$app->request->post('url');
            if(empty($url)){
                return $this->ajaxError();
            }
            $url = trim($url);
            $arr =explode("\n",$url);
            if(count($arr) > 0){
                $arr = array_unique($arr);
                $result = [];//不在库里面的数据
                $tmp = [];
                foreach ($arr as $k =>$item){
                    if($k % 100 == 0){
                        if(!empty($tmp)){
                            $mobile = MobileDetail::find()->select(['mobile'])->where(['in','mobile',$tmp])->column();
                            if(!empty($mobile)){
                                $result = array_merge($result,array_diff($tmp,$mobile));
                            }
                        }
                        $tmp = [];
                    }
                    if(!empty($item) && Com::isMobileNum($item)){
                        $tmp[] = $item;
                    }
                }
                if(!empty($tmp)){
                    $mobile = MobileDetail::find()->select(['mobile'])->where(['in','mobile',$tmp])->column();
                    if(!empty($mobile)){
                        $result = array_merge($result,array_diff($tmp,$mobile));
                    }
                }
                $result = array_unique($result);
                return $this->ajaxSuccess($result);
            }
            return $this->ajaxError();
        }
        return $this->render("mobile");
    }

    public function actionMobileOut(){
        $type = \Yii::$app->request->get('out');
        if($type == '1'){
            $start = \Yii::$app->request->get('start');
            $start = empty($start) ? date('Y-m-d 00:00:00') : date('Y-m-d H:i:s',strtotime($start));
            $end = \Yii::$app->request->get("end");
            $end = empty($end) ? date('Y-m-d 23:59:59') : date('Y-m-d H:i:s',strtotime($end));
            //导出数据
            $query = MobileDetail::find()->where(['>=','created_at',$start])->andWhere(['<=','created_at',$end]);
            $total = $query->count();
            if($total == 0){
                echo '<script>alert("选取的时间，没有记录。请重新选择时间");window.history.go(-1);</script>';
            }
            $pager = new Pagination(['totalCount' => $total]);
            $pager->setPageSize(500);
            $all_page = $pager->getPageCount();
            $objPHPExcel = new \PHPExcel();
            $index = 1;
            for($i =0;$i<$all_page;$i++){
                $pager->setPage($i);
                $list = $query
                    ->alias('`t` force index(index_sort)')
                    ->select(['mobile','operator','province'])//强制走指定的索引
                    ->offset($pager->offset)
                    ->limit($pager->limit)
                    ->orderBy("operator,province")
                    ->asArray()->all();
                if(!empty($list)){
                    foreach($list as $item){
                        $objPHPExcel->setActiveSheetIndex(0)
                            ->setCellValue('A'.$index, $item['mobile'])
                            ->setCellValue('B'.$index, $item['operator'])
                            ->setCellValue('C'.$index, $item['province']);
                        $index++;
                    }
                }
            }
            $name = 'mobile'.date('m.d',strtotime($start)).'-'.date('m.d H:i:s',strtotime($end));
            // Redirect output to a client’s web browser (Excel2007)
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="'.$name.'.xlsx"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
            header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header ('Pragma: public'); // HTTP/1.0

            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }elseif($type == '2'){
            $start = \Yii::$app->request->get('start');
            $start = empty($start) ? date('Y-m-d 00:00:00') : date('Y-m-d H:i:s',strtotime($start));
            $end = \Yii::$app->request->get("end");
            $end = empty($end) ? date('Y-m-d 23:59:59') : date('Y-m-d H:i:s',strtotime($end));

            $list = MobileDetail::find()->select(['count(1) as num','DATE_FORMAT( created_at, "%Y-%m" ) as time'])
                ->where(['>=','created_at',$start])->andWhere(['<=','created_at',$end])
                ->groupBy('time')->asArray()->all();

            $str = '';
            if(!empty($list)){
                foreach($list as $item){
                    $str .= '<p>'.$start.'到'.$end.'有记录：'.$item['num'].'</p>';
                }
            }
            if(empty($str)){
                $str .= '<p>当前时间段，无记录</p>';
            }
            $this->ajaxSuccess($str);
        }else{
            //导出数据界面
            return $this->render('mobile-out');
        }
    }


    public function actionTest(){
        $cai = new Caiji();
        $cai->getSzfangwei();
//        $cai->getFeimu();
    }
    
}

